const LOCAL_KEY = "todomvc";

export interface ITodo {
  id: string;
  title: string;
  completed: boolean;
}

export function fetch() {
  const ret = localStorage.getItem(LOCAL_KEY);
  if (ret) {
    return JSON.parse(ret) as ITodo[];
  } else {
    return [];
  }
}

export function save(todos: ITodo[]) {
  localStorage.setItem(LOCAL_KEY, JSON.stringify(todos));
}

export function generateId() {
  return new Date().getTime() + Math.random().toString(16).substr(2, 4);
}

export function filter(todos: ITodo[], visibility: string) {
  if (visibility === "all") {
    return todos;
  } else if (visibility === "active") {
    return todos.filter((todo) => !todo.completed);
  } else if (visibility === "completed") {
    return todos.filter((todo) => todo.completed);
  }

  throw new Error("Invalid visibility filter");
}
